<template>
  <div v-if="!isAuthLogin" class="c-h c-pt160 c-flex-column c-aligni-center c-p">
    <div class="auth-img-bg"></div>
    <template v-if="companyInfo">
      <img :src="companyInfo.logo || require('@/assets/i/favicon.png')" class="c-ww120 c-hh120 c-br32"/>
      <div class="c-fs30 c-fw-b c-mt40 c-ww580 c-textAlign-c c-fc-xblack">{{companyInfo.companyName}}</div>
    </template>
    <div class="c-fs22 c-mt8 c-fc-gray">登录即可查看详情内容</div>

    <div  :class="isFaShou ? 'c-bg-lblue':'theme-bg'" class="c-mt200 c-fs28 c-fw-b c-fc-white c-textAlign-c c-pv16 c-ww400 c-br38" @click="authLogin()">微信快捷登录</div>
    <div class="c-p c-textAlign-c">
      <div class="c-mt36 c-ww480 c-fs20 c-fc-gray c-lh40" v-if="companyInfo && companyInfo.protocol.length > 0" @click="agreeClick" >
        <span class="iconfont c-fs22 c-lh42 c-fc-gray c-pr4 c-p" :class="isFaShou ? 'c-fc-lblue':'theme-fc'">
          {{isCheckAgreement ? '&#xe796;' : '&#xe6f7;'}}
          <i v-if="isGreeClick" class="bubble">
            请阅读并同意协议
          </i>
        </span>
        <span>已阅读并同意</span>
        <span v-for="item in companyInfo.protocol" :key="item.protocolId" :class="isFaShou ? 'c-fc-lblue':'theme-fc'" @click="goProtcol(item.protocolId)">
          《{{item.name}}》
        </span>
      </div>
    </div>
    <section class="c-w100 c-pb80 mt146" v-if="!specialCustomCid.includes(merchantId)">
      <div class="c-mt40 c-flex-row c-flex-center">
        <div v-if="isVisitor != 1" class="c-ww140 c-flex-column c-flex-center c-mr100" @click="visitorLogin()">
          <div class="c-ww80 c-hh80 c-brp50 c-bg-sgray c-flex-row c-flex-center">
            <i class="iconfont icon-gerenzhongxin c-fs34 c-fc-xblack"></i>
          </div>
          <span class="c-mt18 c-fc-sblack c-fs20">游客模式</span>
        </div>
        <div class="c-ww140 c-flex-column c-flex-center" @click="closeWindow()">
          <div class="c-ww80 c-hh80 c-brp50 c-bg-sgray c-flex-row c-flex-center c-rotateY180">
            <i class="iconfont icon-fenxiang9 c-fs34 c-fc-xblack"></i>
          </div>
          <span class="c-mt18 c-fc-sblack c-fs20 c-ws-n">退出，暂不登录</span>
        </div>
      </div>
    </section>
    <cj-confirm :isShow="isShowComfirm" :option="{title:'服务协议及隐私保护',titleCenter: true,showMasker: true,clickCloseModal: false,showCancelButton: true,cancelButtonText: '取消',confirmButtonText: '同意'}" @onConfirm="agreeClick(); isShowComfirm = false;" @onCancel="isShowComfirm = false;">
      <div class="c-ph40 c-mt22 c-fs24 c-fc-sblack">
        请先阅读并同意
        <span v-for="item in companyInfo.protocol" :key="item.protocolId" class="theme-fc" @click="goProtcol(item.protocolId)">
          《{{item.name}}》
        </span>
      </div>
    </cj-confirm>
  </div>
</template>

<script>
import { utilJs } from "@/utils/common.js"
import { checkApiHp } from '@/utils/apihpCheck';
import CjConfirm from "@/plugin/cjConfirm/cjConfirm.vue";
import { ckjrRequest } from "@/utils/http.js";
export default {
  name: 'WechatAuthPage',
  components: {CjConfirm},
  props: [],
  beforeCreate() {},
  data() {
    return {
      isCheckAgreement: true,
      theme: "mb5_default",
      prodId: '',
      prodType: '',
      merchantId: '',
      refereeId: '',
      companyInfo: null,
      isVisitor: localStorage.getItem("isVisitor") || 0, //1是游客
      isWxApp: true,
      isAuthLogin: true, // 是否静默登录
      isFaShou: localStorage.getItem("isFaShou") == 1,
      isGreeClick: false,
      isShowComfirm: false, // 是否显示协议确认框
      specialCustomCid:['79jee7', '8rxm', '5r4y7'], //私人定制公司id 79jee7:中和应泰  8rxm-测试环境公司id
    }
  },
  created() {
    setDocumentTitle("微信登录");// eslint-disable-line
    this.isFaShou = localStorage.getItem("beforeLoginUrl") ? localStorage.getItem("beforeLoginUrl").includes("fashou/activity") : false;
  },
  mounted() {
    this.$store.commit('updateLoadingStatus', {
      isLoading: false
    });
    let cId = utilJs.getCompanyIdByHerf();
    this.prodId = this.$route.query.prodId || '';
    this.prodType = this.$route.query.prodType || '';
    this.merchantId = cId;
    this.refereeId = localStorage.getItem("refereeId") || this.$route.query.refereeId || '';
    this.isShowComfirm = false;
    this.getCompanyInfo();
    const filterCIds = ['b9mmr8', 'lj7l']; // 中立智道 由于小程序审核影响 受限制的商家开启手动授权登录的流程
    utilJs.getEnv().then(res => {
      this.isWxApp = res === 'wxApp';
      if (res === 'wxApp' && !filterCIds.includes(cId)) { // 小程序环境 && 非过滤商家 走静默登录
        this.isAuthLogin = true
        this.authLogin()
      } else {
        this.isAuthLogin = false
      }
    })
  },
  computed: {},
  methods: {
    agreeClick() {
      this.isCheckAgreement = !this.isCheckAgreement
      this.isGreeClick = !this.isCheckAgreement
    },
    goProtcol(id) {
      this.$routerGo(this, "push", {
        path: "/homePage/agent/protocolInfo",
        query: {
          type: "lecturerPay",
          protocolId: id
        }
      });
    },
    getCompanyInfo() {
      ckjrRequest({url:checkApiHp(`${global.apiurl}protocols/getGeneralProtocol?companyId=${this.merchantId}&fromApp=oa`)})
        .then(response => {
          this.companyInfo = response.data.data;
          this.theme = this.companyInfo.colorName || "mb5_default";
        })
    },
    authLogin() {
      if (this.isCheckAgreement == false && !this.isAuthLogin) {
        this.isGreeClick = true;
        this.isShowComfirm = true;
        return;
      }
      let refereeId = this.refereeId ? this.refereeId : (window.localStorage.getItem("refereeId") ? window.localStorage.getItem("refereeId") : '');
      let shId = window.localStorage.getItem("shareholderId") ? window.localStorage.getItem("shareholderId") : '';
      let md = window.localStorage.getItem("sourceForm") ? window.localStorage.getItem("sourceForm") : '';

      let tf = localStorage.getItem("beforeLoginUrl") && !localStorage.getItem("beforeLoginUrl").includes('homePage/login/wechatAuthPage') && !localStorage.getItem("beforeLoginUrl").includes('homePage/login/bindMobile') && localStorage.getItem("beforeLoginUrl") != "/?t=" ? localStorage.getItem("beforeLoginUrl") : '/';
      if (this.$route.query.beforePath) {
        tf = this.$route.query.beforePath
      }

      if (this.refereeId && tf && !tf.includes('refereeId')) {
        tf = tf + (tf.includes('?') ? '&' : '?') + 'refereeId=' + this.refereeId
      }

      let u = localStorage.getItem("userId") || '';
      if ((navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Adr') > -1) && utilJs.isWeiXin() && localStorage.getItem("companyId")) {
        // 把之前的cookie设置过期，防止cookie不停地增加导致http request 400错误
        let exp = new Date();
        exp.setTime(exp.getTime() - 1);
        document.cookie = localStorage.getItem("companyId") + "|token=;expires=" + exp.toGMTString() + ";path=/";
      }
      window.localStorage.clear();
      window.localStorage.setItem("reservedRefereeId", refereeId);
      window.localStorage.setItem("shareholderId", shId);
      window.localStorage.setItem("sourceForm", md);
      window.localStorage.setItem("beforeLoginUrl", tf);
      utilJs.setStoreId();

      let q = `c=${this.merchantId}&prodId=${this.prodId}&prodType=${this.prodType}`;
      if (this.refereeId) {
        q += `&r=${this.refereeId}`;
      }
      if (u != '' && u != -100) { //-100代表游客
        q = `${q}&u=${u}`;
      }
      if (this.isWxApp) { // 判断小程序环境
        q = `${q}&chl=xcx`;
      }
      if (sessionStorage.getItem('promotedAccountId')) {
        let paId = sessionStorage.getItem('promotedAccountId');
        q = `${q}&promotedAccountId=${paId}`;
      }
      q = `${q}&backUrl=${encodeURIComponent(window.location.href.split("#/")[0] + '#' + tf)}`;

      ckjrRequest({url:checkApiHp(`${global.apiurl}mp/initAuth?${q}`)})
        .then(response => {
          //店铺关闭
          if (response.data.statusCode == 500 && response.data.errorType && response.data.errorType == "companyClose") {
            window.location.replace('https://' + window.location.host + '/closePlatform.html');
            return;
          }
          if (response.data) {
            let ua = window.navigator.userAgent.toLowerCase();
            if (utilJs.isWeiXin() && ua.match(/wxwork/i) == "wxwork") {
              // 企业微信下要删除刚进入的页面地址
              localStorage.removeItem("beforeLoginUrl");
            }
            window.location.replace(response.data + '&time=' + Date.parse(new Date()))
          }
        }).catch(function (error) { });
    },
    //游客
    visitorLogin() {
      let ua = window.navigator.userAgent.toLowerCase();
      let uaText = !!ua.includes('aweme') ? '' : (!!ua.includes('kwai') ? 'ks' : 'llq');
      ckjrRequest({url:`${global.apiurl}common/getAnonUserToken?companyId=${this.merchantId}`, headers:{'X-DMP': uaText}})
        .then(res => {
          window.localStorage.setItem("isVisitor", 1);
          window.localStorage.setItem("companyId", this.merchantId);
          window.localStorage.setItem(this.merchantId, this.merchantId);
          window.localStorage.setItem("userId", res.data.data.u);
          window.localStorage.setItem("token", res.data.data.t);
          window.localStorage.setItem(this.merchantId + "|token", res.data.data.t);
          let isAnd = window.navigator.userAgent.indexOf('Android') > -1 || window.navigator.userAgent.indexOf('Adr') > -1;//andrio终端
          if (isAnd && utilJs.isWeiXin()) {
            let exp = new Date();
            exp.setTime(exp.getTime() + 30 * 24 * 60 * 60 * 1000);
            document.cookie = localStorage.getItem("companyId") + "|token=" + res.data.data.t + ";expires=" + exp.toGMTString() + ";path=/";
          }
          localStorage.setItem("isFaShou", res.data.data.versionType == 12 ? 1 : 0)

          const isFaShou = res.data.data.versionType == 12;
          if (isFaShou) {
            // 如果是发售版跳转到发售邀约列表
            this.$routerGo(this, "push", {
              path: "/fashou/activity",
              query: {
                refereeId: this.refereeId
              }
            });
          } else {
            this.$routerGo(this, "push", {
              path: "/",
              query: {
                refereeId: this.refereeId
              }
            });
          }
        }).catch(function (error) { });
    },
    //拒绝授权自动关闭当前页面
    closeWindow: function (event) {
      localStorage.removeItem("beforeLoginUrl");
      window.WeixinJSBridge.call('closeWindow');
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.auth-img-bg{
  position: absolute;
  left: 0;
  top: 0;
  z-index: -1;
  width: 100%;
  height: 5rem;
  background-image: url('https://ck-bkt-knowledge-payment.oss-cn-hangzhou.aliyuncs.com/admin/material/9_material_admin/image/assets/wechat_auth_bg.jpg');
  background-size: 100%;
  background-repeat: no-repeat;
}
.bubble{
  position: absolute;
  top: 1rem;
  left: -88%;
  height: 1rem;
  width: 4.1rem;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 4px;
  z-index: 1;
  display: flex;
  align-items: center;
  font-size: 0.45rem;
  color: #fff;
  font-style: normal;
  text-align: center;
  display: block;
}
.bubble:after {
  content: "";
  position: absolute;
  top: -0.22rem;
  left: 19%;
  display: block;
  width: 0;
  height: 0;
  border-left: 0.13rem solid transparent;
  border-right: 0.13rem solid transparent;
  border-bottom: 0.24rem solid rgba(0, 0, 0, 0.5);
}
.mt146 {
  margin-top: 3.65rem;
}
</style>